<?php
/**
 * Bos acl token 返回， 用于前端上传文件到 bos
 *
 * @example
 *      （图片 / 视频）等大文件上传
 *
 * Author: Zeon
 * Date: 2017/5/31
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use ZeonWang\BaiduBosClient\Bos;
use ZeonWang\BaiduBosClient\BosInterface;

class TokenController extends Controller
{
    protected $json_token_headers = [
        "Content-type" => "text/javascript; charset=utf-8",
    ];

    /**
     * @param Request $request
     * @param BosInterface|Bos $bos_client
     * @return mixed
     */
    public function index(Request $request, BosInterface $bos_client)
    {
        if ($request->callback)  // for jsonp uptoken
        {
            return $this->assembleJsonpToken($request, $bos_client);
        }
        else  // only sessionToken
        {
            return $bos_client->getSessionToken();
        }
    }

    /**
     * @param Request $request
     * @param BosInterface|Bos $bos_client
     * @return mixed
     */
    public function assembleJsonpToken(Request $request, BosInterface $bos_client)
    {
        $access_control_list = json_decode($request->sts, true);

        $jsonp_token = $bos_client->getJsonpToken($access_control_list);

        $response_payload = sprintf("%s(%s)", $request->callback, $jsonp_token);

        return response($response_payload, Response::HTTP_OK, $this->json_token_headers);
    }
}
